package com.Spring.SpringSpms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.Spring.SpringSpms.model.Complexity;

public class ComplexityDAOImpl implements ComplexityDAO{

	
	private JdbcTemplate jdbcTemplate;
	
	public ComplexityDAOImpl(DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public void saveOrUpdate(Complexity complexity) {
		if (complexity.getComplexity_id() > 0) {
			// update
			String sql = "UPDATE complexity SET complexity_name=? "
						+ "WHERE complexity_id=?";
			jdbcTemplate.update(sql, complexity.getComplexity_name(), complexity.getComplexity_id());
		} else {
			// insert
			String sql = "INSERT INTO complexity (complexity_name)"
						+ " VALUES (?)";
			jdbcTemplate.update(sql, complexity.getComplexity_name());
		}
	
	}

	@Override
	public void delete(int complexityId) {
		String sql = "DELETE FROM complexity WHERE complexity_id=?";
		jdbcTemplate.update(sql, complexityId);

	}

	@Override
	public Complexity get(int complexityId) {
	
		String sql = "SELECT * FROM complexity WHERE complexity_id=" + complexityId;
		return jdbcTemplate.query(sql, new ResultSetExtractor<Complexity>() {

			@Override
			public Complexity extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				if (rs.next()) {
					Complexity complexity = new Complexity();
					complexity.setComplexity_id(rs.getInt("complexity_id"));
					complexity.setComplexity_name(rs.getString("complexity_name"));	
					return complexity;
				}
				
				return null;
			}
			
		});
		
	}

	@Override
	public List<Complexity> list() {
		String sql = "SELECT * FROM complexity";
		List<Complexity> listComplexity = jdbcTemplate.query(sql, new RowMapper<Complexity>() {

			@Override
			public Complexity mapRow(ResultSet rs, int rowNum) throws SQLException {
				
				Complexity complexity = new Complexity();
				
				complexity.setComplexity_id(rs.getInt("complexity_id"));
				complexity.setComplexity_name(rs.getString("complexity_name"));	
				return complexity;
			}
			
		});
		
		return listComplexity;

	}

}